define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'express/package/index?batch_id=' + Config.batch_id,
                    add_url: 'express/package/add',
                    edit_url: 'express/package/edit',
                    del_url: 'express/package/del',
                    multi_url: 'express/package/multi',
                    import_url: 'express/package/import',
                    table: 'express_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'package_no', title: __('包裹号')},
                        {field: 'box_num', title: __('箱数')},
                        {field: 'image', title: __('包裹图'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},

                        {field: 'user.nickname', title: '下单用户',operate:'LIKE',formatter:function (value,row,index) {
                                return row.user ? "<a href=\"javascript:void(0)\" data-tips-image='"+Fast.api.cdnurl(row.user.avatar)+"'><img class=\"img-sm img-center\" src='"+Fast.api.cdnurl(row.user.avatar)+"'></a>&nbsp;" + value : '';
                            }},
                        //状态:0=已入库,1=已预报,2=包裹已出库,3=正在发往澳洲,4=包裹清关中,5=包裹清关完成，等待发往指定地点,6=包裹已抵达指定自提点，等待顾客取件,7=已签收
                        {field: 'state', title: __('State'), searchList: {"0":__('State 0'),"1":__('State 1'),"2":__('State 2'),"3":__('State 3'),"4":__('State 4'),"5":__("State 5"),"6":__("State 6"),"7":__('State 7')}, formatter: Table.api.formatter.normal},
                        {field: 'status', title: __('Status'), searchList: {"waitpackage":__('Status waitpackage'),"batch":__('Status batch'),"delivered":__('Status delivered'),"arrived":__('Status arrived'),"waitingpay":__('Status waitingpay'),"successpay":__('Status successpay')}, formatter: Table.api.formatter.status},
                        {field: 'delivery_weight', title: __('Delivery_weight'), operate:'BETWEEN'},
                        {field: 'delivery_price', title: __('Delivery_price'), operate:'BETWEEN'},
                        {field: 'consignor', title: __('Consignor')},
                       // {field: 'service_price', title: __('增值金额'), operate:'BETWEEN'},
                       // {field: 'discount_price', title: __('优惠金额'), operate:'BETWEEN'},
                       // {field: 'total_price', title: __('支付金额'), operate:'BETWEEN'},
                        // {field: 'service_ids', title: __('增值服务'), operate:false,formatter:function (value,row,index) {
                        //         var html = '';
                        //         for (var i=0;i<row.service.length;i++){
                        //             html += row.service[i].name + '    ' + row.service[i].price + '/单<br>';
                        //         }
                        //
                        //         return html ? html : '无';
                        //     }},
                      //  {field: 'remark', title: __('备注')},
                      //  {field: 'pay_status', title: __('Pay_status'), searchList: {"0":__('未支付'),"1":__('待审核'),"2":__('审核通过'),"3":__('审核未通过')}, formatter: Table.api.formatter.normal},
                      //  {field: 'pay_img', title: __('支付证明'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},

                        {field: 'operate', title: __('Operate'), table: table,buttons: [
                                {
                                    name: 'edit',
                                    text: function(row){
                                        if(row.pay_status==1){
                                            return  __('支付审核');
                                        }else{
                                            return  __('订单详情');
                                        }
                                    },
                                    title: function(row){
                                        if(row.pay_status==1){
                                            return  __('支付审核');
                                        }else{
                                            return  __('订单详情');
                                        }

                                    },
                                    classname:'btn btn-xs btn-editone btn-primary btn-dialog',
                                    icon: 'fa fa-list',
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },



                            ], events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            $(document).on("click", ".btn-addBatch", function () {
                var that = this;
                var id = "addBatchTpl";
                var content = Template(id, {});
                Layer.open({
                    type: 1,
                    title: "加入批次",
                    area: ["500px", "300px"],
                    content: content,
                    success: function (layero) {
                        var form = $("form", layero);
                        var ids = Table.api.selectedids(table);
                        $('#c-ids').val(ids.join(','));
                        Form.api.bindevent(form, function (data) {
                            $(".btn-refresh").trigger("click");
                            Layer.closeAll();
                        });
                    }
                });
            });
            $(document).on("click", "input[name='row[type]']", function () {
                var type = $(this).val();
                if(type == 'old'){
                    $('.batch-select').removeClass('hide')
                }else{
                    $('.batch-select').addClass('hide')
                }
            });
            $(document).on("click", ".btn-invoice", function () {
                if($(this).data('id')){
                    Backend.api.open('express/package/printnew/ids/' + $(this).data('id'), __('打印发货单'),{area:['80%', '80%']});
                }else{
                    Backend.api.open('express/package/printnew/ids/' + Table.api.selectedids(table), __('打印发货单'),{area:['80%', '80%']});
                }
            });

            //自定义export开始
            var submitForm = function (ids, layero) {
                var options = table.bootstrapTable('getOptions');
                console.log(options);
                var columns = [];
                $.each(options.columns[0], function (i, j) {
                    if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
                        columns.push(j.field);
                    }
                });
                var search = options.queryParams({});
                $("input[name=search]", layero).val(options.searchText);
                $("input[name=ids]", layero).val(ids);
                $("input[name=filter]", layero).val(search.filter);
                $("input[name=op]", layero).val(search.op);
                $("input[name=columns]", layero).val(columns.join(','));
                $("form", layero).submit();
            };
            $(document).on("click", ".btn-export", function () {
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;
                console.log(ids, page, all);
                Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl("express/package/export") + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
                    title: '导出数据',
                    //btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    btn: ["选中项(" + ids.length + "条)"],
                    success: function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    }
                    , yes: function (index, layero) {
                        submitForm(ids.join(","), layero);
                        return false;
                    }
                    ,
                    btn2: function (index, layero) {
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        submitForm(ids.join(","), layero);
                        return false;
                    }
                    ,
                    btn3: function (index, layero) {
                        submitForm("all", layero);
                        return false;
                    }
                })
            });
//*************************** 自定义export结束

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
